package com.sparrow.common.util;

import javax.crypto.Cipher;
import java.security.*;
import java.util.Base64;

/**
 * RSA加密解密工具类
 * 1生成密钥对
 * 2使用公钥对信息加密
 * 3使用私钥对密文解密 获得原始信息
 */
public class RSAUtil {

    private static final String RSA = "RSA";

    /**
     * 生成 RSA 密钥对（2048 位）
     */
    public static KeyPair generateKeyPair() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance(RSA);
        generator.initialize(2048);
        return generator.generateKeyPair();
    }

    /**
     * 用公钥加密字符串
     */
    public static String encrypt(String plainText, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));
        return ByteUtil.toBase64(encrypted);
    }

    /**
     * 用私钥解密字符串
     */
    public static String decrypt(String cipherText, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decrypted = cipher.doFinal(ByteUtil.fromBase64(cipherText));
        return new String(decrypted, "UTF-8");
    }

    public static void main(String[] args) throws Exception {
        KeyPair keyPair = RSAUtil.generateKeyPair();
        String message = "message";

        String encrypted = RSAUtil.encrypt(message, keyPair.getPublic());
        System.out.println("Encrypted: " + encrypted);

        String decrypted = RSAUtil.decrypt(encrypted, keyPair.getPrivate());
        System.out.println("Decrypted: " + decrypted);
    }
}

